package sentinel

import (
	. "Go-Easy/pkg/config"
	"encoding/json"
	"errors"
	"fmt"
	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/core/base"
	"github.com/alibaba/sentinel-golang/core/flow"
	"log"
)

//参考: https://sentinelguard.io/zh-cn/docs/golang

func init() {
	err := sentinel.InitDefault()
	if err != nil {
		log.Println("warning sentinel 初始化失败")
		panic(err)
	}

	//在配置文件中有flow rule的情况下，才会做配置
	if len(Sentinel.Flow_Rules) > 0 {
		var rules []*flow.Rule
		for _, v := range Sentinel.Flow_Rules {
			var rule flow.Rule
			if err := json.Unmarshal([]byte(v), &rule); err == nil {
				rules = append(rules, &rule)
			} else {
				fmt.Println("配置文件中sentinel.flow_rule无法转换为flow.Rule对象!")
				panic(err)
			}
		}
		flow.LoadRules(rules)
	} else {
		fmt.Println("没有配置rule,Sentinel不会生效")
	}

}

//流量入站限制
func TrafficInboundRestrict(resource string) error {
	_, b := sentinel.Entry(resource, sentinel.WithTrafficType(base.Inbound))
	if b != nil {
		return errors.New("请求过多；流量配额用尽")
	}
	return nil

}
